package lt.inkredibl.iit;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Point2D;

public class ObsDragPoint
	implements MouseMotionListener, MouseListener, IComponentObserver
{
	private ICoordTransformer _ct;
	private Point2D _pt;
	private Component _c;
	private Contour _cont;
	private boolean _delete;
	private IComponentObserver _cco;

	public ObsDragPoint(Contour cont, ICoordTransformer ct)
	{
		_ct = ct;
		_cont = cont;
	}
	
	public void setConflicting(IComponentObserver cco)
	{
		_cco = cco;
	}
	
	/* (non-Javadoc)
	 * @see lt.inkredibl.iit.IComponentObserver#install(java.awt.Component)
	 */
	public void install(Component c)
	{
		if (_c == null)
		{
			_c = c;
			if (_cco != null)
			{
				_cco.uninstall();
			}
			c.addMouseListener(this);
			c.addMouseMotionListener(this);
		}
		else
		{
			throw new IllegalStateException("Already installed on "+_c+" while trying to install on "+c);
		}
	}
	
	/* (non-Javadoc)
	 * @see lt.inkredibl.iit.IComponentObserver#uninstall()
	 */
	public void uninstall()
	{
		_c.removeMouseListener(this);
		_c.removeMouseMotionListener(this);
		if (_cco != null)
		{
			_cco.install(_c);
		}
		_c = null;
	}

	public void mouseDragged(MouseEvent e)
	{
		_pt.setLocation(_ct.extractPoint(e));
		_c.repaint();
	}

	public void mouseMoved(MouseEvent e)
	{
	}

	public void mouseClicked(MouseEvent e)
	{
	}

	public void mouseEntered(MouseEvent e)
	{
		_delete = false;
	}

	public void mouseExited(MouseEvent e)
	{
		_delete = true;
	}

	public void mousePressed(MouseEvent e)
	{
	}

	public void mouseReleased(MouseEvent e)
	{
		if (_delete)
		{
			_cont.removePoint(_pt);
		}
		else
		{
			_pt.setLocation(_ct.extractPoint(e));
		}
		_pt = null;
		e.consume();
		_c.repaint();
		uninstall();
	}

	public void setPoint(Point2D p)
	{
		_pt = p;
	}

}
